<template>
	<el-cascader
		placeholder="请选择"
		:key="creditCode"
		v-bind="$attrs"
		:props="cascaderProps"
		ref="cascaderEl"
		filterable
		class="w-100"
		@change="handleChange"
	/>
</template>

<script setup lang="ts">
import type { CascaderProps } from 'element-plus'
import apiMod from '@/apiMod'
import bus from '@/utils/eventbus'

const emit = defineEmits(['update:modelName'])

const props = withDefaults(
	defineProps<{
		modelName?: string
		deepLevel?: string | number
	}>(),
	{
		deepLevel: 3,
	}
)

const cascaderEl = ref(null)
let creditCode: string
bus.on('remote-change', (res) => {
	if (res.api == 'view_dpServiceOrgBase_page') {
		creditCode = res.value
	}
})
const cascaderProps: CascaderProps = {
	lazy: true,
	lazyLoad(node, resolve) {
		const { level, data } = node as any
		if (level == 0) {
			apiMod
				.view_dpCommunityHomeBuildingInfo_page({
					pageParaPO: {
						size: 500,
					},
					creditCode,
				})
				.then((res) => {
					const data = res.data
					resolve(
						data.records.map((item) => {
							return {
								...item,
								buildingName: item.buildingName,
								value: item.buildingName,
								label: item.buildingName,
								leaf: level >= props.deepLevel,
							}
						})
					)
				})
		} else if (level == 1) {
			const length = Math.abs(data.buildingFloors)
			resolve(
				Array.from({ length }).map((_, index) => {
					const floor = index + 1
					return {
						...node.data,
						buildingName: data.buildingName,
						belongFloor: floor,
						value: `${floor}`,
						label: floor + '层',
						leaf: level >= props.deepLevel,
					}
				})
			)
		} else if (level == 2) {
			apiMod
				.view_dpCommunityHomeRoomInfo_page({
					pageParaPO: {
						size: 500,
					},
					belongBuilding: data.buildingName,
					floor: data.belongFloor,
					creditCode,
				})
				.then((res) => {
					const data = res.data
					resolve(
						data.records.map((item) => {
							return {
								...item,
								belongBuilding: item.belongBuilding,
								belongFloor: `${item.floor}`,
								belongRoom: item.roomCode,
								value: item.roomCode,
								label: item.roomCode,
								leaf: level >= props.deepLevel,
							}
						})
					)
				})
		} else if (level == 3) {
			apiMod
				.view_dpCommunityHomeBedInfo_page({
					pageParaPO: {
						size: 500,
					},
					belongBuilding: data.belongBuilding,
					belongFloor: data.belongFloor,
					belongRoom: data.belongRoom,
					creditCode,
				})
				.then((res) => {
					const data = res.data
					resolve(
						data.records.map((item) => {
							return {
								...item,
								value: item.bed,
								label: item.bed,
								leaf: level >= props.deepLevel,
							}
						})
					)
				})
		}
	},
}

const handleChange = () => {
	const text = cascaderEl.value?.getCheckedNodes()[0].text
	emit('update:modelName', text)
}
</script>

<style scoped></style>
